<template>
  <div>
    <div class="container">

      <el-page-header @back="goBack" content="" style="padding-bottom: 40px">
        <template v-if="optType === 'update'">
          <span slot="content">修改套餐</span>
        </template>
        <template v-else>
          <span slot="content">新增套餐</span>
        </template>
      </el-page-header>


      <el-form ref="ruleForm"
               :model="ruleForm"
               :rules="rules"
               label-width="180px">
        <div>
          <el-form-item label="套餐名称:"
                        prop="name">
            <el-input v-model="ruleForm.name"
                      placeholder="请填写套餐名称"
                      maxlength="14"/>
          </el-form-item>
          <el-form-item label="套餐分类:"
                        prop="idType">
            <el-select v-model="ruleForm.idType"
                       placeholder="请选择套餐分类">
              <el-option v-for="(item, index) in winepackageList"
                         :key="index"
                         :label="item.name"
                         :value="item.id"/>
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="套餐价格:"
                        prop="price">
            <el-input v-model="ruleForm.price"
                      placeholder="请设置套餐价格"/>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="套餐酒品:"
                        required>
            <el-form-item>
              <div class="addWine">
                <span v-if="wineTable.length == 0"
                      class="addBut"
                      @click="openAddWine('new')">
                  + 添加酒品</span>
                <div v-if="wineTable.length != 0"
                     class="content">
                  <div class="addBut"
                       style="margin-bottom: 20px"
                       @click="openAddWine('change')">
                    + 添加酒品
                  </div>

                  <!--                  选完酒品后才会展示出来-->
                  <div class="table">
                    <el-table :data="wineTable"
                              style="width: 100%">
                      <el-table-column prop="name"
                                       label="名称"
                                       width="150"
                                       align="center"/>
                      <el-table-column prop="price"
                                       label="原价"
                                       width="100"
                                       align="center">
                        <template slot-scope="scope">
                          {{ (Number(scope.row.price).toFixed(2) * 100) / 100 }}
                        </template>
                      </el-table-column>
                      <el-table-column prop="address"
                                       label="份数"
                                       align="center">
                        <template slot-scope="scope" >
                          <el-input-number v-model="scope.row.copies"
                                           size="small"
                                           :min="1"
                                           :max="99"
                                           style="width:200px"
                                           label="描述文字"/>
                        </template>
                      </el-table-column>
                      <el-table-column prop="address"
                                       label="操作"
                                       width="100px;"
                                       align="center">
                        <template slot-scope="scope">
                          <el-button type="text"
                                     size="small"
                                     class="delBut non"
                                     @click="delWineHandle(scope.$index)">
                            删除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>


                </div>
              </div>
            </el-form-item>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="套餐图片:"
                        required
                        prop="image">

            <img-upload :prop-image-url="imageUrl"
                          @imageChange="imageChange">
              图片大小不超过2M<br>仅能上传 PNG JPEG JPG类型图片<br>建议上传200*200或300*300尺寸的图片
            </img-upload>
          </el-form-item>
        </div>
        <div class="address">
          <el-form-item label="套餐描述:">
            <el-input v-model="ruleForm.description"
                      type="textarea"
                      :rows="3"
                      maxlength="200"
                      placeholder="套餐描述，最长200字"/>
          </el-form-item>
        </div>

        <div>
          <div class="subBox">
            <el-button type="primary" @click="submitForm('ruleForm',false)">保存</el-button>
            <el-button
                v-if="this.optType ==='add'"
                type="primary"
                @click="submitForm('ruleForm',true)">保存并继续添加套餐
            </el-button>
          </div>
        </div>
      </el-form>

      <!--      表单-->
      <el-dialog v-if="dialogVisible"
                 title="添加酒品"
                 class="addWineList"
                 :visible.sync="dialogVisible"
                 width="60%"
                 :modal-append-to-body="false"
                 :before-close="handleClose">
<!--        <el-input v-model="value"-->
<!--                  class="seachWine"-->
<!--                  placeholder="请输入酒品名称进行搜索"-->
<!--                  style="width: 293px; height: 40px"-->
<!--                  size="small"-->
<!--                  clearable>-->
<!--          <i slot="prefix"-->
<!--             class="el-input__icon el-icon-search"-->
<!--             style="cursor: pointer"-->
<!--             @click="seachHandle"/>-->
<!--        </el-input>-->
        <AddWine v-if="dialogVisible"
                 ref="addwine"
                 :check-list="checkList"
                 :wine-list="wineList"
                  @checkList="checkListValue"/>
<!--                 :seach-key="seachKey"-->
        <span slot="footer"
              class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary"
                   @click="addTableList">添 加</el-button>
      </span>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import request from "@/utils/request";
import AddWine from "./components/addWine";
import ImgUpload from "@/components/ImgUpload.vue";

export default {
  components: {
    AddWine,
    ImgUpload,
  },
  data() {
    return {
      value: '',
      winepackageList: [],
      seachKey: '',
      wineList: [],
      imageUrl: '',
      wineTable: [],
      dialogVisible: false,
      checkList: [],

      title: '',
      optType: 'add',

      ruleForm: {
        categoryId: '',
        price: '',
        code: '',
        image: '',
        description: '',
        wineList: [],
        status: true,
        idType: ''
      },
      rules: {
        name: [
          {required: true, message: '套餐名称', trigger: 'blur'},
          {validator: this.validator, trigger: 'blur'}
        ],
        idType: {required: true, message: '请选择套餐分类', trigger: 'change'},
        image: {required: true, message: '酒品图片不能为空'},
        price: [
          {required: true, message: '请输入价格', trigger: 'blur'},
          {validator: this.pricce, trigger: 'blur'}
        ],
      },

    }
  },
  created() {
    //看是否携带参数过来，携带的话就使用更新
    // 查询套餐分类，用于填充查询页面的下拉框
    request.get(`/admin/category/list/${2}`).then(res => {
      if (res.code == 1) {
        this.winepackageList = res.data
      }
    })

    this.optType = this.$route.query.id ? 'update' : 'add'
    if (this.optType === 'update') {
      request.get(`/admin/winepackage/${this.$route.query.id}`).then(res => {
        if (res.code == 1) {
          this.ruleForm = res.data
          this.ruleForm.status = res.data.status
          this.ruleForm.price = res.data.price
          this.imageUrl = res.data.image
          this.checkList = res.data.winepackageWines
          this.ruleForm.idType = res.data.categoryId
          this.wineTable = res.data.winepackageWines.reverse()
        } else {
          this.$message.error(res.msg)
        }
      })
    }
  },
  methods: {
    goBack() {
      const currentRoute = this.$route.path;
      if (currentRoute !== '/winepackage') {
        this.$router.push('/winepackage');
      }
    },
    pricce(rule, value, callback) {
      const reg = /^([1-9]\d{0,5}|0)(\.\d{1,2})?$/
      if (!reg.test(value) || Number(value) <= 0) {
        callback(
            new Error(
                '请输入大于零且最多保留两位小数的金额'
            )
        )
      } else {
        callback()
      }
    },
    validator(rule, value, callback) {
      const reg = /^[\u4e00-\u9fa5_a-zA-Z]{1,10}$/
      if (!value) {
        callback(new Error('请输入套餐名称'))
      } else if (!reg.test(value)) {
        callback(new Error('名称输入不符，请输入1-10个字符'))
      } else {
        callback()
      }
    },

    delWineHandle(index) {
      this.wineTable.splice(index, 1)
      this.checkList = this.wineTable
      // this.checkList.splice(index, 1)
    },
    // 添加酒品
    openAddWine(st) {
      // this.seachKey = ''
      this.dialogVisible = true
    },
    handleClose(done) {
      // this.$refs.addwine.close()
      this.dialogVisible = false
      this.checkList = JSON.parse(JSON.stringify(this.wineTable))
      // this.dialogVisible = false
    },

    checkListValue(checkedListAll){
      this.checkList = JSON.parse(JSON.stringify(checkedListAll))
    },
    // 保存添加酒品列表
    addTableList() {
      this.wineTable = JSON.parse(JSON.stringify(this.checkList))
      this.wineTable.forEach((n) => {
        n.copies = 1
      })
      this.dialogVisible = false
    },
    // seachHandle() {
    //   this.seachKey = this.value
    // },

    submitForm(formName, isContinue) {
      //$refs是引用的ref属性，通过ref可以获取到组件实例，通过实例可以调用组件的方法
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.wineTable.length === 0) {
            return this.$message.error('套餐下酒品不能为空')
          }
          if (!this.ruleForm.image) return this.$message.error('套餐图片不能为空')
          this.ruleForm.winepackageWines = this.wineTable.map((obj) => ({
            copies: obj.copies,
            wineId: obj.wineId,
            name: obj.name,
            price: obj.price
          }))
          this.ruleForm.status = this.optType === 'add' ? 0 : this.ruleForm.status ? 1 : 0
          this.ruleForm.categoryId = this.ruleForm.idType
          if (this.optType === 'add') {      //新增操作
            request.post('/admin/winepackage', this.ruleForm).then(res => {
              if (res.code === 1) {
                this.$message.success('套餐添加成功！')
                if (isContinue) {
                  this.$refs.ruleForm = {
                    wineList: [],
                    wineTable: [],
                    ruleForm: {
                      name: '',
                      categoryId: '',
                      price: '',
                      code: '',
                      image: '',
                      description: '',
                      wineList: [],
                      status: true,
                      id: '',
                      idType: ''
                    },
                    imageUrl: ''
                  }
                } else {
                  this.$router.push('/winepackage')
                }
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {     //修改操作
            request.put('/admin/winepackage', this.ruleForm).then(res => {
              if (res.code === 1) {
                this.$message.success('修改成功')
                this.$router.push('/winepackage')
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    imageChange(value) {
      this.ruleForm.image = value
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-input {
  width: 200px;
}

.container {
  position: relative;
  z-index: 1;
  background: #fff;
  padding: 30px;
  border-radius: 4px;

  .subBox {
    padding-top: 30px;
    text-align: center;
    border-top: solid 1px $gray-5;
  }

}

.addBut {
  background: #409EFF;
  display: inline-block;
  padding: 0px 20px;
  border-radius: 3px;
  line-height: 40px;
  cursor: pointer;
  border-radius: 4px;
  color: white;
  font-weight: 500;
}
.table {
  border: solid 1px #ebeef5;
  border-radius: 3px;

  th {
    padding: 5px 0;
  }

  td {
    padding: 7px 0;
  }
}


</style>
